// eslint-disable-next-line @typescript-eslint/no-use-before-define
import DEL_ICON from '@/assets/image/del_sm.png';
import DOC_ICON from '@/assets/image/doc.png';
import { articlesBulk } from '@/services/ant-design-pro/knowledge';
import { getFileSize } from '@/utils';
import { FileAddOutlined } from '@ant-design/icons';
import type { TabsProps, UploadProps } from 'antd';
import { Button, Input, message, Modal, Tabs, Upload } from 'antd';
import mammoth from 'mammoth';
import React, { useEffect, useRef, useState } from 'react';
import { styles } from './style';

const UploadDoc: React.FC<any> = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [activeKey, setActiveKey] = useState<string>('1');
  const [inputDraft, setInputDraft] = useState<string>('');
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [fileList, setFileList] = useState<any>([]);
  const { TextArea } = Input;
  const { Dragger } = Upload;
  const { updateOpenDoc, open, knowledgeId } = props;
  const headerUploadRef = useRef(null);

  useEffect(() => {
    setIsOpen(open);
  }, []);

  const readFileContent = (file: any) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = async (loadEvent: any) => {
        const arrayBuffer = loadEvent.target['result'];
        try {
          const resultObject = await mammoth.extractRawText({ arrayBuffer: arrayBuffer });
          let wordTxt = resultObject.value;
          if (wordTxt.length > 3000) {
            file.fileStatus = '超出3000字限制';
            message.warning(`(${file.name}) 超出3000字限制！`);
          } else {
            file.fileStatus = 'normal';
            file.title = file.name.split('.')[0];
            file.content = wordTxt;
          }
          resolve(file);
        } catch (error) {
          console.log('=====error======', error);
          file.fileStatus = '文件格式有误';
          message.warning(`(${file.name}) 文件格式有误！`);
          resolve(file);
        }
      };
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });
  };

  const upLoadProps: UploadProps = {
    name: 'file',
    accept: '.docx, .doc, .md, .txt',
    action: '',
    headers: {},
    multiple: true,
    maxCount: 7,
    disabled: fileList.length > 6,
    showUploadList: false,
    beforeUpload: () => {
      // return readFileContent(file);
      return false;
    },
    onChange: async (filer: any) => {
      console.log('==filer=', filer);
      if (filer.file?.status !== 'uploading') {
        await readFileContent(filer.file);
        const files = filer.fileList.map((file: any) => {
          if (file.uid === filer.file.uid) {
            file.originFileObj = filer.file;
          }

          return file;
        });
        setFileList(files);
      }
      if (filer.file?.status === 'done') {
        message.success(`${filer.file.name} file uploaded successfully`);
      } else if (filer.file?.status === 'error') {
        message.error(`${filer.file.name} file upload failed.`);
      }
    },
    style: { height: '260px' },
  };

  const onInputChange = (e: any) => {
    setInputDraft(e.target.value);
  };

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `手动输入`,
      children: (
        <TextArea
          value={inputDraft}
          showCount
          rows={12}
          maxLength={3000}
          placeholder="请输入文档"
          onChange={onInputChange}
          style={{ marginBottom: 16 }}
        />
      ),
    },
    {
      key: '2',
      label: `本地文档`,
      children: (
        <div style={{ background: '#F9FAFC', borderRadius: '6px', border: '1px solid #DBDFEC' }}>
          <Dragger ref={headerUploadRef} {...upLoadProps} style={{ border: 'none' }}>
            {fileList?.length > 0 ? (
              <div style={{ height: '348px', padding: '0 15px' }}>
                {fileList.map((item: any, index: React.Key | null | undefined) => {
                  return (
                    <div key={index} style={styles.fileCard}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src={DOC_ICON} alt="" width={26} height={26} />
                        <div style={{ marginLeft: '12px' }}>{item?.name.substring(0, 15)}</div>
                        {item?.originFileObj.fileStatus !== 'normal' && (
                          <div style={{ marginLeft: '10px', color: 'red' }}>
                            {item.originFileObj.fileStatus}
                          </div>
                        )}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div style={{ marginRight: '100px' }}>{getFileSize(item?.size)}</div>
                        <img
                          src={DEL_ICON}
                          width={14}
                          height={16}
                          alt=""
                          style={{ cursor: 'pointer' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            const fileListCopy = [...fileList];
                            fileListCopy.splice(index, 1);
                            if (headerUploadRef.current) {
                              headerUploadRef.current.fileList.splice(index, 1);
                            }
                            setFileList(fileListCopy);
                          }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div>
                <p className="ant-upload-drag-icon" style={{ marginTop: '70px', fontSize: '18px' }}>
                  <FileAddOutlined />
                </p>
                <p className="ant-upload-text" style={{ marginBottom: '70px', fontSize: '14px' }}>
                  点击选择文档，或直接拖拽文档到此，单次最多上传7个文档
                </p>
              </div>
            )}
          </Dragger>
        </div>
      ),
    },
  ];

  const tabChange = (e: any) => {
    setActiveKey(e);
  };

  const handleCancel = () => {
    setLoading(false);
    setFileList([]);
    setIsOpen(false);
    updateOpenDoc(false);
  };

  const handleOk = async () => {
    setLoading(true);
    const articles: any[] = [];
    if (inputDraft) {
      const title = inputDraft.trim().split('\n')[0].substring(0, 10);
      const content = inputDraft;
      articles.push({ title, content });
    }
    fileList.map((file: any) => {
      const { originFileObj } = file;
      if (originFileObj.content) {
        articles.push({
          title: originFileObj.title,
          content: originFileObj.content,
        });
      }
      return {};
    });

    if (articles.length > 0) {
      const params: any = { articles };
      if (knowledgeId) {
        params.knowledge_base_id = knowledgeId;
      }
      const res = await articlesBulk(params);
      if (res.code === 0) {
        message.success('上传成功');
        handleCancel();
      } else {
        message.error(res.msg);
        setLoading(false);
      }
    } else {
      setLoading(false);
      message.error('无可上传的文件！');
    }
  };

  return (
    <div>
      <Modal
        title="上传文档"
        open={isOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={'600px'}
        footer={[
          <div
            key="1"
            style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
          >
            {/* <Checkbox checked={checked} onChange={() => setChecked(!checked)}>打开作为参考文档使用</Checkbox> */}
            <div></div>
            <div style={{ gap: '20px' }}>
              <Button onClick={handleCancel} style={styles.button}>
                取消
              </Button>
              <Button
                type="primary"
                loading={loading}
                onClick={handleOk}
                style={{ ...styles.button, background: '#397BFF' }}
              >
                上传
              </Button>
            </div>
          </div>,
        ]}
      >
        <Tabs defaultActiveKey="1" items={items} activeKey={activeKey} onChange={tabChange}></Tabs>
      </Modal>
    </div>
  );
};

export default UploadDoc;
